<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Tools\SynMsgTask;
use App\Admin\Extensions\Tools\SynTask;
use App\Handlers\RedisHandler;
use App\Models\MsgTask;
use App\Models\RateType;
use App\Models\Task;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Widgets\Table;
use Illuminate\Foundation\Auth\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\MessageBag;

class MsgTaskController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('消息任务调度');
            $content->description('');
//            $content->row(view('admin.lineChart'));
            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('消息任务调度');
            $content->description('');

            $content->body($this->form('edit')->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('消息任务调度');
            $content->description('');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(MsgTask::class, function (Grid $grid) {

            $grid->model()->orderByDesc('id');
            $grid->id('ID')->sortable();
            $grid->column('name','任务名');
            $grid->column('max_device_num','最大任务');
            $grid->column('ip','ip');
            $grid->column('port','端口');
            $grid->column('dtype','设备类型');
            $grid->column('max_adress','收信人个数');
            $grid->column('status','状态')->sortable()->display(function ($value){
                $statusColor = config('system.msgTask.status_color')[$value];
                return "<span class=\"label label-$statusColor\">".config('system.msgTask.status')[$value]."</span>";
            });
            $grid->column('type', '广告类型')->sortable()->display(function ($value) {
                return config('system.ad_task.type')[$value];
            });
            $grid->column('link', '广告链接');
            $grid->column('target_num','当前/目标阅读')->sortable()->display(function ($value){
                return "{$this->current_num}/{$this->target_num}";
            });
            $grid->column('enable', '启用')->switch(config('system.switch.states'))->sortable();
            $grid->created_at('创建时间')->sortable();
            $grid->filter(function (Grid\Filter $filter){
                $filter->like('name','任务名');
                $filter->equal('enable', '启用')->select([1 => '启用', 2 => '禁用']);
                $filter->equal('status','状态')->select(config('system.msgTask.status'));
                $filter->between('created_at','创建时间')->date();
            });
//            $grid->actions(function($actions){
//                $actions->disableDelete();
//                $actions->append('<a class="btn btn-primary btn-xs" href="'.url('admin/msg-task/msgdelete',['id'=>$this->getKey()]).'">删除</a>');
//            });
            $grid->tools(function ($tools){
                $tools->append(new SynMsgTask());
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($mode='create')
    {
        return Admin::form(MsgTask::class, function (Form $form) use($mode) {
            $form->display('id', 'ID');
            $form->text('name','任务名');
            $form->text('dtype','设备类型');
            $form->text('ip','ip');
            $form->text('port','端口');
            $form->text('max_adress','收信人个数');
            $form->file('file_column','收信人文件txt形式');
            $form->textarea('content','任务正文');
            $form->select('type', '广告类型')->options(config('system.ad_task.type'))->default(AD_TASK_TEXT_AND_IMG_TYPE);
            $form->number('target_num','目标阅读数')->default(1000)->rules('integer|required');
            $form->number('max_device_num','最大设备数')->default(5)->rules('integer|required');
            $form->select('status','状态')->options(config('system.msgTask.status'))->default(MSG_STATUS_RUNNING);
            $form->multipleImage('pictures', '任务图片')->removable();
            $form->textarea('urls', '图片URL')->help('一行一个,如果填写图片URL，将优先使用URL');
            $form->text('link', '任务链接');
            $form->switch('enable', '启用')->default(1)->states(config('system.switch.states'));
            $form->display('created_at', '创建时间');
            $form->saved(function (Form $form) {
                if($form->model()->file_column){
                    $this->next($form->model()->id);
                }
                if(empty($form->model()->file_column)&&$form->model()->status ==1){
//                    RedisHandler::rebuild($form->model()->id);
                    (new RedisHandler())->rebuild($form->model()->id);
                    return ['status_code' => 200, 'message' => '重建队列成功'];
                }
            });
        });
    }



    public function sync()
    {
        RedisHandler::syncMsgTasks();
        return ['status_code' => 200, 'message' => '同步成功'];
    }

    public function clear()
    {
        RedisHandler::clearMachine();
        return ['status_code' => 200, 'message' => '清空成功'];
    }

    public function rebuild()
    {
        (new RedisHandler())->rebuild();
        return ['status_code' => 200, 'message' => '重建队列成功'];
    }
    public function next($id)
    {
        $txt =MsgTask::where("id", $id)->get()->first()->file_column;
        $t =storage_path('app/public/'.$txt);
        $file = fopen($t,"r");
        $data= array();
        $i=0;
        while(!feof($file))
        {
            $data[$i]= fgets($file);//fgets()函数从文件指针中读取一行
            $i++;
        }
        $data = array_filter($data);
        $redis = app('redis');
        $redis->pipeline(function ($pipe) use ($data,$id){
            foreach ($data as $k=>$v){
                $pipe->rpush("msg:txt:".$id, trim($v));
            }
        });
        fclose($file);
//        file_put_contents('t.txt' , var_export($t, true),FILE_APPEND);
    }



}
